/*
 * @Author: sunkai@xinxinapp.cn
 * @Date: 2021-03-09 14:22:26
 * @LastEditTime: 2021-03-10 09:37:59
 * @LastEditors: sunkai@xinxinapp.cn
 * @Description:
 * @FilePath: /edu/src/utils/request.ts
 */
import qs from 'qs'
import axios from 'axios'
import store from '@/store/index'
import { Message } from 'element-ui'
import router from '@/router/index'

const redirectLogin = () => {
  router.push({
    name: 'login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}

const refreshToken = () => {
  return axios.create()({
    method: 'POST',
    url: '/front/user/refresh_token',
    data: qs.stringify({
      refreshtoken: store.state.user.refresh_token
    })
  })
}

const request = axios.create({
})

request.interceptors.request.use((config) => {
  if (store.state.user && store.state.user.access_token) {
    config.headers.Authorization = store.state.user.access_token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

let isRefresh = false
let requests: any[] = []
request.interceptors.response.use((response) => {
  if (response.data.state === 401) {
  }
  return response
}, async (error) => {
  if (error.response) {
    const { status } = error.response
    if (status === 400) {
      Message.error('请求参数错误')
    } else if (status === 401) {
      if (!store.state.user) {
        redirectLogin()
        return Promise.reject(error)
      }
      if (!isRefresh) {
        isRefresh = true
        return refreshToken().then(res => {
          if (!res.data.success) {
            throw new Error('刷新 Token 失效')
          }
          store.commit('setUser', res.data.content)
          requests.forEach(cb => cb())
          requests = []
          return request(error.config)
        }).catch((error) => {
          store.commit('setUser', null)
          redirectLogin()
          return Promise.reject(error)
        }).finally(() => {
          isRefresh = false
        })
      }
      return new Promise(resolve => {
        requests.push(() => {
          resolve(request(error.config))
        })
      })
    } else if (status === 403) {
      Message.error('没有权限，请联系管理员')
    } else if (status === 404) {
      Message.error('请求资源不存在')
    } else if (status >= 500) {
      Message.error('服务端错误，请联系管理员')
    }
  } else if (error.request) {
    Message.error('请求超时')
  } else {
    Message.error('请求失败')
  }
  return Promise.reject(error)
})

export default request
